package cn.byapps.attendance.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.byapps.attendance.entity.Job;
import cn.byapps.attendance.service.JobService;
import cn.byapps.attendance.util.DataTablesResult;
import core.controller.BaseController;

@Controller
@RequestMapping("/wechat/job")
public class JobController extends BaseController {

	@Resource
	private JobService jobService;

	@RequestMapping(value = { "index", "/", "" })
	public String index() {
		return "/wechat/job/index";
	}

	@RequestMapping(value = { "getData" }, method = RequestMethod.POST)
	public void getData(Integer draw, Long start, Long length, HttpServletResponse response) {
		int pos = 0;
		int rows = 10;
		if (start != null) {
			pos = start.intValue();
		}
		if (length != null) {
			rows = length.intValue();
		}
		DataTablesResult<Job> lists = jobService.getData(draw, pos, rows);
		if (lists == null) {
			lists = new DataTablesResult<Job>();
		}
		try {
			this.writeJSON(response, lists);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add() {
		return "wechat/job/add";
	}

	@RequestMapping(value = "update", method = RequestMethod.GET)
	public String update(String id, Model model) {
		int nId = Integer.parseInt(id);
		Job ad = jobService.get(nId);
		model.addAttribute("item", ad);
		return "wechat/job/update";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(Job job) {
		jobService.update(job);
		return "redirect:index";
	}

	@RequestMapping(value = "use", method = RequestMethod.GET)
	public String update(String id) {
		int nId = Integer.parseInt(id);
		jobService.updateFlag(nId);
		return "redirect:index";
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	public String add(Job job, HttpServletRequest request, Model model) throws IOException {
		jobService.save(job);
		return "redirect:index";
	}
}
